package com.lagou.kafka.demo.deserializer;

import com.lagou.kafka.demo.entity.User;
import org.apache.kafka.common.serialization.Deserializer;


import java.nio.ByteBuffer;
import java.util.Map;

/**
 * @param
 * @author oyz
 * @version 1.0.4
 * @description: 用户反序列化
 * @date 2022/6/6 21:11
 */
public class UserDeserializer implements Deserializer<User> {
    @Override
    public void configure(Map<String, ?> configs, boolean isKey) {

    }

    @Override
    public User deserialize(String topic, byte[] data) {
        ByteBuffer allocate = ByteBuffer.allocate(data.length);
        allocate.put(data);
        // 反转缓存区,把position的值(当前元素的读取位置)赋值给limit属性,然后position置为0，方便日后进行get操作
        allocate.flip();
        // 读取接下来缓存区当前位置往后的四个字节
        final int userId = allocate.getInt();
        // 读取接下来缓存区当前位置往后的四个字节
        final int userNameLength = allocate.getInt();
        String userName = new String(data,8,userNameLength);
        return new User(userId,userName);
    }

    @Override
    public void close() {

    }
}
